import json
import logging

from django.utils import timezone
from rest_framework.decorators import action
from rest_framework.decorators import api_view
from rest_framework.response import Response
from rest_framework import status
from rest_framework import viewsets

from celery_tasks.sms import tasks
from common import translate_lang
from dbcv import serializers
from dbcv import models
from users_manage.redis_token import redis_connect

logger = logging.getLogger("default")


class TestAPIView(viewsets.GenericViewSet):

    # action中不添加 url_path='fun_url' 的话,默认该类url路由的最后一个连接名为函数名：get_test_tb
    @action(methods=['post'], detail=False, permission_classes=())
    def get_test_tb(self, request):
        try:
            serializer = serializers.TestApiDeserialization(data=request.data)
            token_key = request.META.get("HTTP_TOKEN")
            redis_data = redis_connect.get(token_key)
            logger.info("============= redis_data = {}".format(json.loads(redis_data)))
            logger.info("============= request token = {}".format(token_key))
            if not serializer.is_valid():
                return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST)
            # 处理验证后的数据
            validated_data = serializer.validated_data
            logger.info("validated_data = {}".format(validated_data))
            _id = validated_data['id']
            query_data = models.TestTable.objects.filter(id=_id).first()

            data_dict = {"id": query_data.id,
                         "name": query_data.name,
                         "author": query_data.author,
                         "create_date": query_data.create_date,
                         }
            # print(data_dict)
            logger.info("get_test_tb data_dict = {}".format(data_dict))
            data = serializers.TestApiSerializer(data_dict).data
            return Response({'msg': "成功", 'data': data, 'code': 200}, status=status.HTTP_200_OK)
        except Exception as e:
            raise e


@api_view(['GET'])
def test(request):
    """
    测试token
    """
    current_time = timezone.now()
    print("当前时间是：{}".format(current_time))
    result = tasks.send_sms.delay("视图调用celery任务")
    print('登录的用户名是:', request.user)
    res_data = {'data': {'status_code': 200}}
    return Response(**res_data)


class TranslateAPIView(viewsets.GenericViewSet):

    @action(methods=['post'], detail=False, permission_classes=())
    def get_translate(self, request):
        serializer = serializers.TranslateSerializer(data=request.data)
        if not serializer.is_valid():
            return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST)
        text = serializer.validated_data['text']
        from_lang = serializer.validated_data['from_lang']
        to_lang = serializer.validated_data['to_lang']
        result_text = translate_lang.translate_text(text, from_lang, to_lang)
        return Response({'msg': "成功", 'data': result_text, 'code': 200}, status=status.HTTP_200_OK)